//
//  YXDataManager.m
//  YXImageBrowserDemo
//
//  Created by guo peng huang on 2021/5/18.
//

#import "YXDataManager.h"
#import "YXImageBrowser+Internal.h"

@implementation YXDataManager {
    __weak YXImageBrowser *_browser;
    NSCache<NSNumber *, id<YXDataProtocol>> *_dataCache;
}

- (instancetype)initWithBrowser:(YXImageBrowser *)browser {
    if (self = [super init]) {
        _browser = browser;
        _dataCache = [NSCache new];
    }
    return self;
}

- (NSInteger)numberOfCells {
    /// 判断当前数据源 是否实现协议返回  如果有 就通过协议 没有就走原始方法
    return _browser.dataSource ? [_browser.dataSource yx_numberOfCellsInImageBrowser:_browser] : _browser.dataSourceArray.count;
}

- (id<YXDataProtocol>)dataForCellAtIndex:(NSInteger)index {
    if (index < 0 || index > self.numberOfCells - 1) { /// 越界
        return nil;
    }
    /// 读取缓存
    id<YXDataProtocol> data = [_dataCache objectForKey:@(index)];
    /// 判断缓存是否存在
    if (!data) {
        /// 没有缓存 从数据源中读取数据
        data = _browser.dataSource ? [_browser.dataSource yx_imageBrowser:_browser dataForCellAtIndex:index] : _browser.dataSourceArray[index];
        /// 放入缓存
        [_dataCache setObject:data forKey:@(index)];
        [_browser implementBaseInfoProtocol:data];
    }
    return data;
}

- (void)clear {
    [_dataCache removeAllObjects];
}

- (void)preloadWithPage:(NSInteger)page {
    if (_preloadCount == 0) return;
    
    NSInteger left = -(_preloadCount / 2), right = _preloadCount - ABS(left);
    for (NSInteger i = left; i <= right; ++i) {
        if (i == 0) continue;
        id<YXDataProtocol> targetData = [self dataForCellAtIndex:page + i];
        if ([targetData respondsToSelector:@selector(yx_preload)]) {
            [targetData yx_preload];
        }
    }
}

#pragma mark - getters & setters

- (void)setDataCacheCountLimit:(NSUInteger)dataCacheCountLimit {
    _dataCacheCountLimit = dataCacheCountLimit;
    _dataCache.countLimit = dataCacheCountLimit;
}

@end
